package com.Dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import util.DBHelp;
import util.RowMapper;

import com.entity.Project;

public class ProjectDao {

	private DBHelp<Project> db = new DBHelp<Project>();

	public List<Project> findById(int id) {
		String sql = "SELECT * FROM t_project WHERE id IN(SELECT projectid FROM t_employee_project WHERE employeeid = ?) order by createtime desc";

		return db.queryForList(sql, new Mr(), id);
	}

	class Mr implements RowMapper<Project> {
		public Project mapperRow(ResultSet rs) throws SQLException {
			Project em = new Project();
			em.setId(rs.getInt("id"));
			em.setName(rs.getString("name"));
			em.setDesc(rs.getString("desc"));
			em.setCreatetime(rs.getString("createtime"));
			return em;
		}

	}

	private int select(String name, String desc, String createtime) {
		String sql = "SELECT id,`name`,`desc`,createtime FROM `t_project` WHERE  `name`=? and `desc`=? and createtime=?";
		Project p = db.queryForObject(sql, new Mr(), name, desc, createtime);
		if (p != null) {
			return p.getId();
		}else{
			return -1;
		}
	}

	public int save(Project p) {
		String sql = "INSERT INTO t_project(`name`,`desc`,createtime)VALUES(?,?,?)";
		db.executeSQL(sql, p.getName(), p.getDesc(), p.getCreatetime());
		return select(p.getName(), p.getDesc(), p.getCreatetime());
	}

	public void update(Project p) {
		String sql = "UPDATE t_project SET `name`= ?,`desc`= ? WHERE id = ?";
		db.executeSQL(sql, p.getName(), p.getDesc(), p.getId());
	}

}
